package com.khaliil.kkadmin.demo.sse.client;

import okhttp3.*;
import okio.BufferedSource;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkhttpSseClient {

    public static void main(String[] args) throws InterruptedException {
        OkhttpSseClient sseClient = new OkhttpSseClient();
        sseClient.test();
        TimeUnit.SECONDS.sleep(60);
    }

    public void test() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(0, TimeUnit.SECONDS);
        builder.writeTimeout(10, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/demoSse/mvcSse")
                .header("Accept", "text/event-stream")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.err.println("Error occurred: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    BufferedSource source = response.body().source();
                    while (!source.exhausted()) {
                        String line = source.readUtf8Line();
                        System.out.println("Received: " + line);
                    }
                } else {
                    System.err.println("Request failed: " + response.message());
                }
            }
        });
    }
}
